//
//  AppDelegate.m
//  firstpoint
//
//  Created by 王旭阳 on 2017/6/20.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "AppDelegate.h"
#import "RootTabBarViewController.h"//根视图
#import "LoginViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AlipaySDK/AlipaySDK.h>
#define USHARE_DEMO_APPKEY @"5861e5daf5ade41326001eab"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    BOOL landed = false;
    if (landed) {
    RootTabBarViewController*vc=[RootTabBarViewController new];
    self.window.rootViewController=vc;
    }else{
        LoginViewController*vc=[LoginViewController new];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:vc];
        
        self.window.rootViewController=nav;
    }
    /*高德地图*/
    [AMapServices sharedServices].apiKey =@"06eef37f159d363c63a2250d4b030ba4";
    
    
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:USHARE_DEMO_APPKEY];
    
    [self configUSharePlatforms];
    
//    [self confitUShareSettings];
    
    return YES;
}
- (void)configUSharePlatforms
{
    /*
     设置微信的appKey和appSecret
     [微信平台从U-Share 4/5升级说明]http://dev.umeng.com/social/ios/%E8%BF%9B%E9%98%B6%E6%96%87%E6%A1%A3#1_1
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:nil];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     100424468.no permission of union id
     [QQ/QZone平台集成说明]http://dev.umeng.com/social/ios/%E8%BF%9B%E9%98%B6%E6%96%87%E6%A1%A3#1_3
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106322260"/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
    /*
     设置新浪的appKey和appSecret
     [新浪微博集成说明]http://dev.umeng.com/social/ios/%E8%BF%9B%E9%98%B6%E6%96%87%E6%A1%A3#1_2
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"197685108"  appSecret:@"966ec72bd77136bab649ef775ea56d08" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}
//#define __IPHONE_10_0    100000
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
#pragma mark-----9.0后的方法，为了适配低版本
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响。
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                
                
                NSInteger orderState=[resultDic[@"resultStatus"] intValue];
                if (orderState==9000) {
                    NSString *allString=resultDic[@"result"];
                    NSString * FirstSeparateString=@"\"&";
                    NSString *  SecondSeparateString=@"=\"";
                    NSMutableDictionary *dic=[self VEComponentsStringToDic:allString withSeparateString:FirstSeparateString AndSeparateString:SecondSeparateString];
                    NSLog(@"ali=%@",dic);
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:nil userInfo:dic];
                    //成功
                    //                    [self alipaySccesswith:@"20"];//掉后台接口
                }else{
                    NSString *returnStr;
                    switch (orderState) {
                        case 8000:
                            returnStr=@"订单正在处理中";
                            break;
                        case 4000:
                            returnStr=@"订单支付失败";
                            break;
                        case 6001:
                            returnStr=@"订单取消";
                            break;
                        case 6002:
                            returnStr=@"网络连接出错";
                            break;
                            
                        default:
                            break;
                    }
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:returnStr delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    [alertview show];
                }
                
            }];
            
            // 授权跳转支付宝钱包进行支付，处理支付结果
            //        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            //            NSLog(@"result = %@",resultDic);
            //            // 解析 auth code
            //            NSString *result = resultDic[@"result"];
            //            NSString *authCode = nil;
            //            if (result.length>0) {
            //                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            //                for (NSString *subResult in resultArr) {
            //                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
            //                        authCode = [subResult substringFromIndex:10];
            //                        break;
            //                    }
            //                }
            //            }
            //            NSLog(@"授权结果 authCode = %@", authCode?:@"");
            //        }];
            return YES;
        }
    }
    return result;
}

#endif
#pragma mark-----微信9.0前的方法，为了适配低版本

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
        //支付宝
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                NSLog(@"result = %@",resultDic);
                NSInteger orderState=[resultDic[@"resultStatus"] integerValue];
                if (orderState==9000) {
                    
                    //成功
//                    [self alipaySccesswith:@"20"];//掉后台接口
                    
                }else{
                    NSString *returnStr;
                    switch (orderState) {
                        case 8000:
                            returnStr=@"订单正在处理中";
                            break;
                        case 4000:
                            returnStr=@"订单支付失败";
                            break;
                        case 6001:
                            returnStr=@"订单取消";
                            break;
                        case 6002:
                            returnStr=@"网络连接出错";
                            break;
                            
                        default:
                            break;
                    }
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:returnStr delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    [alertview show];
                }
            }];
            
            //        // 授权跳转支付宝钱包进行支付，处理支付结果
            //        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            //            NSLog(@"result = %@",resultDic);
            //            // 解析 auth code
            //            NSString *result = resultDic[@"result"];
            //            NSString *authCode = nil;
            //            if (result.length>0) {
            //                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            //                for (NSString *subResult in resultArr) {
            //                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
            //                        authCode = [subResult substringFromIndex:10];
            //                        break;
            //                    }
            //                }
            //            }
            //            NSLog(@"授权结果 authCode = %@", authCode?:@"");
            //        }];
            return YES;
        }
    }
    return result;
}
#pragma mark-----9.0后的方法，为了适配低版本

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                NSInteger orderState=[resultDic[@"resultStatus"] integerValue];
                if (orderState==9000) {
                    NSString *allString=resultDic[@"result"];
                    NSString * FirstSeparateString=@"\"&";
                    NSString *  SecondSeparateString=@"=\"";
                    NSMutableDictionary *dic=[self VEComponentsStringToDic:allString withSeparateString:FirstSeparateString AndSeparateString:SecondSeparateString];
                    NSLog(@"ali=%@",dic);
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:nil userInfo:dic];
                    //成功
//                    [self alipaySccesswith:@"20"];//掉后台接口
                }else{
                    NSString *returnStr;
                    switch (orderState) {
                        case 8000:
                            returnStr=@"订单正在处理中";
                            break;
                        case 4000:
                            returnStr=@"订单支付失败";
                            break;
                        case 6001:
                            returnStr=@"订单取消";
                            break;
                        case 6002:
                            returnStr=@"网络连接出错";
                            break;
                            
                        default:
                            break;
                    }
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:returnStr delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    [alertview show];
                }
                
            }];
            
            // 授权跳转支付宝钱包进行支付，处理支付结果
            //        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            //            NSLog(@"result = %@",resultDic);
            //            // 解析 auth code
            //            NSString *result = resultDic[@"result"];
            //            NSString *authCode = nil;
            //            if (result.length>0) {
            //                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            //                for (NSString *subResult in resultArr) {
            //                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
            //                        authCode = [subResult substringFromIndex:10];
            //                        break;
            //                    }
            //                }
            //            }
            //            NSLog(@"授权结果 authCode = %@", authCode?:@"");
            //        }];
            return YES;
        }

    }
    return result;
}
/**
 *  支付宝返回字段解析
 *
 *  @param AllString            字段
 *  @param FirstSeparateString  第一个分离字段的词
 *  @param SecondSeparateString 第二个分离字段的词
 *
 *  @return 返回字典
 */

-(NSMutableDictionary *)VEComponentsStringToDic:(NSString*)AllString withSeparateString:(NSString *)FirstSeparateString AndSeparateString:(NSString *)SecondSeparateString{
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    
    NSArray *FirstArr=[AllString componentsSeparatedByString:FirstSeparateString];
    
    for (int i=0; i<FirstArr.count; i++) {
        NSString *Firststr=FirstArr[i];
        NSArray *SecondArr=[Firststr componentsSeparatedByString:SecondSeparateString];
        [dic setObject:SecondArr[1] forKey:SecondArr[0]];
        
    }
    
    return dic;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
